//
//  ZMScale.swift
//  hrhtv
//
//  Created by zd on 20/02/1447 AH.
//

import UIKit

public struct ZMScale {
    static let baseSize = CGSize(width: 375, height: 812)
    static let minScale: CGFloat = 0.85
    static let maxScale: CGFloat = 1.25
    
    static var scale: CGFloat {
        let screenSize = UIScreen.main.bounds.size
        let sx = screenSize.width / baseSize.width
//        let sy = screenSize.height / baseSize.height
        return min(max(sx, minScale), maxScale)
    }
}

public extension CGFloat {
    var s: CGFloat { self * ZMScale.scale }
}

public extension UIFont {
    func scaled() -> UIFont {
        self.withSize(self.pointSize * ZMScale.scale)
    }
}

public extension UIView {
    /// 递归缩放当前 view 及其子视图的约束和字体
    func applyScaleRecursively() {
        let s = ZMScale.scale
        
        // 调整自身的圆角等
        if layer.cornerRadius > 0 {
            layer.cornerRadius *= s
        }
        
        // 调整约束常量
        for constraint in constraints {
            constraint.constant *= s
        }
        
        // 字体缩放
        if let label = self as? UILabel, let font = label.font {
            label.font = font.scaled()
        } else if let btn = self as? UIButton, let font = btn.titleLabel?.font {
            btn.titleLabel?.font = font.scaled()
        } else if let textField = self as? UITextField, let font = textField.font {
            textField.font = font.scaled()
        } else if let textView = self as? UITextView, let font = textView.font {
            textView.font = font.scaled()
        }
        
        // 递归子视图
        for sub in subviews {
            sub.applyScaleRecursively()
        }
    }
}

